package org.luckystrophe.snowtoms;

import java.io.File;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.manager.ImageManager;
import org.luckystrophe.snowtoms.manager.SnowtomsUtils;
import org.luckystrophe.snowtoms.model.impl.PostActivityIntent;
import org.luckystrophe.snowtoms.model.impl.RequestMessage;
import org.luckystrophe.snowtoms.pref.UserPreference_;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.androidquery.AQuery;
import com.googlecode.androidannotations.annotations.AfterInject;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.res.DrawableRes;
import com.googlecode.androidannotations.annotations.res.StringArrayRes;
import com.googlecode.androidannotations.annotations.res.StringRes;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;

@EActivity(R.layout.activity_post)
public class PostActivity extends SherlockActivity implements TextWatcher {

	@DrawableRes(R.drawable.btn_send)
	Drawable sendIcon;

	@ViewById(R.id.et_writearea)
	EditText et_writePost;

	@ViewById(R.id.btn_attachpicture)
	ToggleButton btn_attachPicture;

	@ViewById(R.id.iv_selectphototumbnail)
	ImageView iv_selectedPhotoThumbnail;

	@ViewById(R.id.btn_attachlocation)
	ToggleButton btn_attachLocation;

	@StringArrayRes(R.array.imagepostoptions)
	String[] imageFrom;

	@StringRes(R.string.pleaseWait)
	String pleaseWait;

	@StringArrayRes(R.array.setLocation)
	String[] location;

	@StringArrayRes(R.array.seoul)
	String[] fixedLocation;

	MenuItem sendPostMessage;

	String[] finalLocationArray;

	@Pref
	UserPreference_ pref;

	@Bean
	RequestMessage postNoochi;

	@Bean
	SnowtomsUtils utils;

	private AQuery aq;

	private ProgressDialog mProgressDialog;

	private PostActivityIntent postActivityIntent;

	public static final String POST_OPTION = "postOption";

	public static final int TAKE_GALLERY = 0;

	public static final int TAKE_CAMERA = 1;

	Uri selectItem = null;

	@AfterInject
	public void afterInject() {
		aq = new AQuery(this);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.post, menu);
		sendPostMessage = menu.findItem(R.id.btn_menu_send);
		sendPostMessage.setEnabled(false);
		sendPostMessage.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				menuSendMessage();
				return false;
			}
		});
		return super.onCreateOptionsMenu(menu);
	}

	@AfterViews
	public void afterViews() {
		Intent receiveIntent = getIntent();
		postActivityIntent = (PostActivityIntent) receiveIntent.getParcelableExtra(POST_OPTION);
		if (postActivityIntent == null) {
			finishActivity();
			return;
		}

		final ActionBar actionbar = getSupportActionBar();
		actionbar.setTitle(postActivityIntent.getActivityTitle());

		btn_attachLocation.setChecked(postActivityIntent.isStrictSetLocation());
		et_writePost.addTextChangedListener(this);

		if (postActivityIntent.isStrictSetImage()) {
			if (pref.location().get().isEmpty()) {
				finalLocationArray = postActivityIntent.isStrictSetImage() ? fixedLocation : location;
				AlertDialog.Builder listBuilder = new AlertDialog.Builder(this);
				listBuilder.setTitle("지역구를 선택해 주세요.");
				listBuilder.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						if (pref.location().get().isEmpty()) {
							btn_attachLocation.setChecked(false);
						}
					}
				});
				listBuilder.setItems(finalLocationArray, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						if (item == 0 && finalLocationArray.length == 26) {
							pref.location().remove();
							return;
						}
						pref.location().put(finalLocationArray[item]);
						chooseImageFrom(postActivityIntent.isStrictSetImage());
					}
				});
				AlertDialog alertList = listBuilder.create();
				alertList.show();

			} else {
				chooseImageFrom(postActivityIntent.isStrictSetImage());
			}
		}
	}

	public void menuSendMessage() {
		String messageBody = et_writePost.getText().toString();

		if (mProgressDialog != null && mProgressDialog.isShowing()) {
			return;
		}

		if (postActivityIntent.getMessageType() == PostActivityIntent.AUTH_MESSAGE) {
			if (!btn_attachLocation.isChecked()) {
				Toast.makeText(this, "지역을 설정해 주세요.", Toast.LENGTH_SHORT).show();
				return;
			}

			if (selectItem == null) {
				Toast.makeText(this, "이미지를 꼭 첨부해야 합니다.", Toast.LENGTH_SHORT).show();
				return;
			}
		}
		mProgressDialog = ProgressDialog.show(this, "", pleaseWait, true);
		postNoonchi(messageBody, postActivityIntent.getMessageType());
	}

	@Background
	public void sendPostMessageWriting(String comment) {

	}

	@Background
	public void postNoonchi(String comment, int messageType) {
		try {
			JSONObject resultJo = postNoochi.tempFileUpload(selectItem, comment, pref.name().get(), messageType,
					btn_attachLocation.isChecked());
			afterPostNoonchi(resultJo, messageType);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			afterPostNoonchi(null, 0);
		}
	}

	@UiThread
	void afterPostNoonchi(JSONObject resultJo, int messageType) {
		ImageManager.deleteTmpFile(selectItem);
		if (mProgressDialog != null && mProgressDialog.isShowing()) {
			mProgressDialog.dismiss();
		}
		Intent intent = new Intent();
		intent.putExtra("messageType", messageType);
		intent.setAction("Post DONE!");
		setResult(RESULT_OK, (intent));
		finishActivity();
	}

	@SuppressWarnings("deprecation")
	@Click(R.id.btn_attachpicture)
	public void touchAttachPicture() {
		if (btn_attachPicture.isChecked()) {
			btn_attachPicture.setChecked(false);
			chooseImageFrom(true);

		} else {
			selectItem = null;
			iv_selectedPhotoThumbnail.setBackgroundDrawable(null);
			iv_selectedPhotoThumbnail.setVisibility(View.GONE);
		}
	}

	@Click(R.id.btn_attachlocation)
	public void touchAttachLocation() {

		if (btn_attachLocation.isChecked() && !pref.location().get().isEmpty()) {
			Toast.makeText(this, pref.location().get() + "에서 눈을 치우셨나요?", Toast.LENGTH_SHORT).show();
			return;
		}

		if (pref.location().get().isEmpty() || !btn_attachLocation.isChecked()) {
			btn_attachLocation.setChecked(!btn_attachLocation.isChecked());
			utils.setLocationDialog(this, postActivityIntent.isStrictSetLocation(), new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					if (postActivityIntent.isStrictSetImage()) {
						btn_attachLocation.setChecked(true);
					} else {
						btn_attachLocation.setChecked(false);
					}
				}
			}, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finalLocationArray = postActivityIntent.isStrictSetLocation() ? fixedLocation : location;
					if (which == 0 && finalLocationArray.length == 26) {
						pref.location().remove();
						btn_attachLocation.setChecked(false);
						return;
					}
					pref.location().put(finalLocationArray[which]);
					btn_attachLocation.setChecked(true);
				}
			});
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}

		if (requestCode == TAKE_GALLERY || requestCode == TAKE_CAMERA) {
			selectItem = data.getData();
			File original_file = ImageManager.getImageFile(selectItem, getContentResolver());
			selectItem = ImageManager.createSaveCropFile();
			File copy_file = new File(selectItem.getPath());
			ImageManager.copyFile(original_file, copy_file);

			if (data != null) {
				iv_selectedPhotoThumbnail.setVisibility(View.VISIBLE);
				btn_attachPicture.setChecked(true);
				aq.id(iv_selectedPhotoThumbnail).image(new File(selectItem.getPath()), 140);
				Toast.makeText(this, "사진삭제는 '카메라 아이콘'을 다시 눌러주세요.", Toast.LENGTH_SHORT).show();
				btn_attachPicture.setChecked(true);
			}
		}

	}

	public void chooseImageFrom(boolean isStrictSetImage) {
		if (!isStrictSetImage) {
			return;
		}
		AlertDialog.Builder listBuilder = new AlertDialog.Builder(this);
		listBuilder.setTitle("사진선택");
		listBuilder.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				btn_attachPicture.setChecked(false);
			}
		});
		listBuilder.setItems(imageFrom, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {

				if (item == 0) {
					Intent intent = new Intent(Intent.ACTION_PICK);
					intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
					startActivityForResult(intent, TAKE_GALLERY);

				} else if (item == 1) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent, TAKE_CAMERA);
				}
			}
		});
		AlertDialog alertList = listBuilder.create();
		alertList.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finishActivity();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void finishActivity() {
		ImageManager.deleteTmpFile(selectItem);
		finish();
		overridePendingTransition(R.anim.leftin, R.anim.rightout);
	}

	@Override
	public void afterTextChanged(Editable s) {
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		sendPostMessage.setEnabled(s.length() > 0);

	}

}
